package look4ss.aplicativo;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.sdsmdg.tastytoast.TastyToast;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import de.hdodenhof.circleimageview.CircleImageView;

public class ActivityEditarPerfil extends AppCompatActivity {
    private CircleImageView imagemPersonalizar;
    private Button botaoFinalizar;
    private Uri imagemUrl = null;
    private ProgressDialog carregandoTela;
    private EditText editarEmail;
    private EditText editarSenha;
    private EditText definirNome;
    private TextView textoEmail;
    private TextView textoSenha;
    private TextView textoNome;
    private TextView apagarConta;
    private TextView desconectarConta;
    private SharedPreferences sharp;
    private static final int ESCOLHER_IMAGEM = 1;
    public String nome_pessoa;
    public FirebaseAuth fauth = FirebaseAuth.getInstance();
    public FirebaseUser usuario = FirebaseAuth.getInstance().getCurrentUser();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_perfil);

        if (usuario == null) {
            startActivity(new Intent(ActivityEditarPerfil.this, ActivityLogin.class));
            ActivityLogin.ir = "config";
            finish();
        }
        carregandoTela = new ProgressDialog(this);
        imagemPersonalizar = findViewById(R.id.imagemConfig);
        editarEmail = findViewById(R.id.editarEmail);
        editarSenha = findViewById(R.id.editarSenha);
        definirNome = findViewById(R.id.definirNome);
        botaoFinalizar = findViewById(R.id.botaoConcluir);
        apagarConta = findViewById(R.id.apagarConta);
        desconectarConta = findViewById(R.id.desconectarConta);

        textoEmail = findViewById(R.id.textoEmail);
        textoSenha = findViewById(R.id.textoSenha);
        textoNome = findViewById(R.id.textoNome);
        carregarFotoPerfil();
        sharp = getSharedPreferences("usuario", Context.MODE_PRIVATE);
        nome_pessoa = sharp.getString("nome", "");

        botaoFinalizar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                personalizarConta();
            }
        });

        apagarConta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                perguntarExclusaoConta();
            }
        });

        desconectarConta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fauth.signOut();
                sharp = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor edtr = sharp.edit();
                edtr.putString("email", "");
                edtr.putString("senha", "");
                edtr.apply();
                startActivity(new Intent(ActivityEditarPerfil.this, ActivityLogin.class));
                finish();
            }
        });

        imagemPersonalizar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            }
        });
        comecarEdicao();
    }

    private void carregarFotoPerfil() {
        try {
            final ProgressBar carregandoFoto;
            carregandoFoto = findViewById(R.id.fotoCarregando);
            String imagemAtualUrl = variaveisGlobais.urlFotosPerfilFirebase + usuario.getUid() + ".jpg?alt=media";
            Picasso.get().load(imagemAtualUrl).fit().memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imagemPersonalizar, new com.squareup.picasso.Callback() {
                public void onSuccess() {
                    carregandoFoto.setVisibility(View.GONE);
                }

                public void onError(Exception ex) {
                    TastyToast.makeText(ActivityEditarPerfil.this, getString(R.string.erro_carregar_imagem), Toast.LENGTH_LONG, TastyToast.ERROR);
                    carregandoFoto.setVisibility(View.GONE);
                }
            });
        } catch (NullPointerException e) {
            //
        }
    }

    private void comecarEdicao() {
        try {
            textoEmail.setText(usuario.getEmail());
            textoSenha.setText("*********");
            textoNome.setText(nome_pessoa);

            if ("".equals(nome_pessoa)) {
                textoNome.setText(R.string.erro_nome_nao_add);
                textoNome.setError(getString(R.string.tu_deve_informar_nome));
                definirNome.setError(getString(R.string.tu_deve_informar_nome));
                definirNome.setHint(R.string.digite_nome);
            }

            textoEmail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textoEmail.setVisibility(View.GONE);
                    editarEmail.setText(usuario.getEmail());
                    editarEmail.setVisibility(View.VISIBLE);

                }
            });
            textoSenha.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textoSenha.setVisibility(View.GONE);
                    editarSenha.setVisibility(View.VISIBLE);

                }
            });
            textoNome.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textoNome.setVisibility(View.GONE);
                    definirNome.setText(nome_pessoa);
                    definirNome.setVisibility(View.VISIBLE);

                }
            });
        } catch (NullPointerException e) {
            //
        }
    }

    private void personalizarConta() {
        final String email_novo = editarEmail.getText().toString();
        final String senha_nova = editarSenha.getText().toString();
        String nome = definirNome.getText().toString();

        if (editarEmail.getText().toString().equals(usuario.getEmail())) {
            TastyToast.makeText(getApplicationContext(), getString(R.string.email_novo_igual_atual), Toast.LENGTH_SHORT, TastyToast.WARNING);
        }
        if (definirNome.getText().toString().equals(nome_pessoa)) {
            TastyToast.makeText(getApplicationContext(), getString(R.string.nome_novo_igual_atual), Toast.LENGTH_SHORT, TastyToast.WARNING);
        }

        if (!email_novo.equals("") && !editarEmail.getText().toString().equals(usuario.getEmail())) {
            carregandoTela.setMessage(getString(R.string.carregando));
            carregandoTela.show();

            usuario.updateEmail(email_novo)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                TastyToast.makeText(getApplicationContext(), getString(R.string.email_alterado_suc), Toast.LENGTH_SHORT, TastyToast.SUCCESS);
                            }
                            sharp = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor edtr = sharp.edit();
                            edtr.putString("email", email_novo);
                            edtr.apply();
                            carregandoTela.dismiss();
                            startActivity(new Intent(ActivityEditarPerfil.this, ActivityLogin.class));
                        }
                    });
        }

        if(senha_nova.trim().length() < 8){
            textoSenha.setError(getString(R.string.senha_curta));
            editarSenha.setError(getString(R.string.senha_curta));
        }

        if (!senha_nova.equals("") && senha_nova.trim().length() > 7) {
            carregandoTela.setMessage(getString(R.string.carregando));
            carregandoTela.show();

            usuario.updatePassword(senha_nova)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                TastyToast.makeText(getApplicationContext(), getString(R.string.senha_alterada_suc), Toast.LENGTH_SHORT, TastyToast.SUCCESS);
                            }
                            sharp = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor edtr = sharp.edit();
                            edtr.putString("senha", senha_nova);
                            edtr.apply();

                            carregandoTela.dismiss();
                            startActivity(new Intent(ActivityEditarPerfil.this, ActivityLogin.class));
                        }
                    });
        }

        if (!nome.equals("") && !definirNome.getText().toString().equals(nome_pessoa)) {
            sharp = getSharedPreferences("usuario", Context.MODE_PRIVATE);
            SharedPreferences.Editor edtr = sharp.edit();
            edtr.putString("nome", nome);
            edtr.apply();

            carregandoTela.dismiss();
            TastyToast.makeText(getApplicationContext(), getString(R.string.nome_alterado_suc), Toast.LENGTH_SHORT, TastyToast.SUCCESS);
            startActivity(new Intent(ActivityEditarPerfil.this, ActivityEditarPerfil.class));
        }

        if (imagemUrl != null) {
            carregandoTela.setMessage(getString(R.string.carregando));
            carregandoTela.show();
            try {
                String idUsuario_imagem = FirebaseAuth.getInstance().getCurrentUser().getUid();
                StorageReference filepath = FirebaseStorage.getInstance().getReference().child("imagens_perfil/" + idUsuario_imagem + ".jpg");
                filepath.putFile(imagemUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        carregandoTela.dismiss();

                        carregarFotoPerfil();
                        TastyToast.makeText(getApplicationContext(), getString(R.string.foto_alterada_suc), Toast.LENGTH_SHORT, TastyToast.SUCCESS);
                        startActivity(new Intent(ActivityEditarPerfil.this, ActivityEditarPerfil.class));

                    }
                });
            } catch (NullPointerException npe) {
                //
            }
        }
    }

    @Override
    protected void onActivityResult(int codigoRequisicao, int codigoResultado, Intent data) {
        try {
            super.onActivityResult(codigoRequisicao, codigoResultado, data);
            Uri UriImagem = data.getData();
            if (codigoRequisicao == ESCOLHER_IMAGEM && codigoResultado == RESULT_OK && UriImagem != null) {
                CropImage.activity(UriImagem)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(this);
            }
            if (codigoRequisicao == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                if (codigoResultado == RESULT_OK) {
                    imagemUrl = result.getUri();
                    imagemPersonalizar.setImageURI(imagemUrl);
                } else if (codigoResultado == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    Exception erro = result.getError();
                }
            }
        } catch (NullPointerException npex) {
            //
        }
    }

    private void perguntarExclusaoConta() {
        Context c = this;
        AlertDialog.Builder b = new AlertDialog.Builder(c);
        b.setTitle(R.string.tem_certeza_sobre_excluir_conta_titulo);
        b.setMessage(R.string.tem_certeza_sobre_excluir_conta_descricao);
        b.setCancelable(true);
        b.setIcon(R.drawable.icone_xis);
        b.setNeutralButton(
                R.string.nao_fazer_cancelar_acao,
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface d, int id) {
                        return;
                    }
                });
        b.setNegativeButton(
                R.string.excluir_apenas_conta,
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface d, int id) {
                        apagarConta();
                    }
                });
        b.setPositiveButton(
                R.string.excluir_conta_e_tudo_mais,
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface d, int id) {
                        apagarEnvios();
                        apagarConta();
                    }
                });
        AlertDialog alerta = b.create();
        alerta.show();
    }

    private void apagarConta() {
        carregandoTela.setMessage(getString(R.string.encerrando_conta));
        carregandoTela.show();
        usuario.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    sharp = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edtr = sharp.edit();
                    edtr.putString("email", "");
                    edtr.putString("senha", "");
                    edtr.apply();
                    fauth.signOut();
                    carregandoTela.dismiss();
                    TastyToast.makeText(ActivityEditarPerfil.this, getString(R.string.encerrar_conta_suc), Toast.LENGTH_SHORT, TastyToast.INFO);
                    finish();
                } else {
                    TastyToast.makeText(ActivityEditarPerfil.this, getString(R.string.encerrar_conta_erro), Toast.LENGTH_SHORT, TastyToast.ERROR);
                }
            }
        });
    }

    private void apagarEnvios() {
        final String idConta = usuario.getUid();
        new Thread(new Runnable() {
            public void run() {
                try {
                    Document d = Jsoup.connect(variaveisGlobais.urlApiApagarTudo)
                            .data("idUsuario", idConta)
                            .post();
                    fauth.signOut();
                } catch (Exception e) {
                    //k
                }
            }
        }).start();
    }
    }
